﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using RMS.Common;

namespace Demo.Manage.Web.Controllers
{
    public class RMSAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }
        /// <summary>
        /// 重写授权检查
        /// </summary>
        /// <param name="httpContext">Http内容</param>
        /// <returns>是否授权</returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //var nlog = LogManager.GetCurrentClassLogger();
            #region 检测Action是否包含匿名访问标签
            if (httpContext.AllowAsyncDuringSyncStages)
            {
                return true;
            }
            #endregion
            
            #region httpContext验证
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            #endregion
            #region 登录验证
            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }
            #endregion
            #region 访问链接权限认证
            string requestUrl = HttpContext.Current.Request.Url.AbsolutePath;//站点名+页面名
            var virtualDirectory = ConfigHelper.GetAppValue("VirtualDirectory");
            if (requestUrl.StartsWith(virtualDirectory))//如果有虚拟目录需要删除虚拟目录
            {
                requestUrl = requestUrl.Substring(virtualDirectory.Length);
            }
            #region 首页不进行权限认证
            if (string.IsNullOrWhiteSpace(requestUrl))
            {
                return true;
            }
            requestUrl = "/" + requestUrl.Trim('/').ToLower();
            if (requestUrl == "/" || requestUrl == "/home" || requestUrl == "/home/index" || requestUrl == "/index/default")
            {
                return true;
            }
            #endregion
            #region 链接权限认证
            var menus = BaseController.Menu;
            if (menus == null || menus.Count < 1)
            {
                return false;
            }
            if (!menus.Where(p => p.Url != null).Any(p => p.UrlAbsolutePath.ToLower() == requestUrl))
            {
                return false;
            }
            #endregion
            #endregion
            return true;
        }

        /// <summary>
        /// 重写没有权限时的操作
        /// </summary>
        /// <param name="filterContext">过滤器内容</param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            string httpMethod = filterContext.HttpContext.Request.HttpMethod;
            #region POST
            if (httpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    //ajax的POST请求
                    filterContext.Result = new JsonResult { Data = new CommonOutPutVm { Message = "权限不足！" } };
                    return;
                }
                else
                {
                    //POST执行
                    filterContext.HttpContext.Response.Redirect("~/Home/Login", true);
                    return;
                }
            }
            #endregion
            #region GET
            else if (httpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    //ajax的GET请求
                    filterContext.Result = new RedirectResult("~/Error/NoPermissions");
                    return;
                }
                else
                {
                    //GET执行
                    filterContext.Result = new RedirectResult("~/Home/Login");
                    return;
                }
            }
            #endregion
            #region 其他
            else
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
            #endregion
        }
    }
}